package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.dto.OrdersDto;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jialin
 * @create 2023-07-03 13:20
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 用户订单分页显示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page<OrdersDto>> userPage(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        Page<OrdersDto> ordersDtoPage = new Page<>();
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, userId)
                .orderByDesc(Orders::getCheckoutTime).orderByDesc(Orders::getOrderTime);
        orderService.page(ordersPage, queryWrapper);
        BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
        List<Orders> ordersRecords = ordersPage.getRecords();
        List<OrdersDto> orderDtoRecords = ordersRecords.stream().map((item) -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(orderDtoRecords);
        return R.success(ordersDtoPage);
    }

    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        return R.success(null);
    }

    /**
     * 所有用户订单分页显示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Orders>> page(int page, int pageSize, String number, String beginTime, String endTime) {
        String pattern = "yyyy-MM-dd HH:mm:ss";
        LocalDateTime begin = null;
        LocalDateTime end = null;
        if(beginTime != null && endTime != null) {
            begin = LocalDateTime.parse(beginTime, DateTimeFormatter.ofPattern(pattern));
            end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern(pattern));
        }
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Strings.isNotEmpty(number), Orders::getNumber, number)
                .orderByDesc(Orders::getCheckoutTime).orderByDesc(Orders::getOrderTime);
        if(begin!= null && begin.isBefore(end)) queryWrapper.between(Orders::getOrderTime, begin, end);
        orderService.page(ordersPage, queryWrapper);
        return R.success(ordersPage);
    }

    /**
     * 订单状态修改
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Orders orders) {
        Orders order = orderService.getById(orders.getId());
        order.setStatus(orders.getStatus());
        orderService.updateById(order);
        return R.success("订单状态修改成功");
    }
}
